package api

import (
	"RedWork/dao"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
)

type Phone_Sort struct {
	Brand     string
	PowerMin  string
	PowerMax  string
	ScreenMin string
	ScreenMax string
	IPV6      string
	Code      string
}

func GetPhoneSort() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.JSON(200, gin.H{
			"品牌": []string{"苹果", "华为", "小米", "荣耀", "OPPO", "vivo",
				"三星", "realme", "魅族", "其他"},
			"屏幕尺寸":   []string{"6.0-6.24英寸", "6.85-6.94英寸", "6.75-6.84英寸", "6.65-6.74英寸"},
			"充电功率":   []string{"100W-200W", "50-100W", "40-49W", "30-39W", "20-29W", "10-19W", "1-10W"},
			"支持IPv6": []string{"支持IPv6", "不支持IPv6"},
		})
	}
}

func GetSort() gin.HandlerFunc {
	return func(c *gin.Context) {
		var PhoneSort dao.Phone_Sort
		PhoneSort.IfTwo = false
		var data interface{}
		status := true

		search := c.Query("search")
		PhoneSort.Brand = c.Query("brand")
		changePower := c.Query("changing_power")
		PhoneSort.IPV6 = c.Query("ipv6")
		size := c.Query("screen_size")
		price := c.Query("price")
		sort_code := c.Query("sort")
		store_id := c.Query("store_id")

		if search != "" {
			PhoneSort.Search = search
		}
		if sort_code != "" { //按一般非价格排序
			PhoneSort.Code = sort_code
			if price != "" {
				PhoneSort.IfTwo = true //在价格区间进行排序
				PhoneSort.PriceMin, PhoneSort.PriceMax = HandlePrice(price)
			}
		} else if price != "" && sort_code == "" { //只筛选价格
			PhoneSort.Code = "0"
			PhoneSort.PriceMin, PhoneSort.PriceMax = HandlePrice(price)
		}

		if size != "" {
			PhoneSort.ScreenMin, PhoneSort.ScreenMax = HandleScreenSize(size)
		}
		if changePower != "" {
			PhoneSort.PowerMin, PhoneSort.PowerMax = HandlePower(changePower)
		}
		if store_id != "" {
			PhoneSort.StoreID = store_id
		}

		if status == true {
			data = dao.QueryPhone(PhoneSort)
		}

		json := map[string]interface{}{
			"status": status,
			"data":   data,
		}
		//fmt.Println(string(marshal))
		c.JSON(200, json)
	}
}

func HandleScreenSize(size string) (min string, max string) {
	//other := false
	size = strings.TrimFunc(size, func(r rune) bool {
		if r == '英' || r == '寸' {
			return true
		}
		return false
	})
	split := strings.Split(size, "-")
	min = split[0]
	max = split[1]
	return
}

func HandlePower(power string) (min string, max string) {
	power = strings.TrimFunc(power, func(r rune) bool {
		if r == 'W' {
			return true
		}
		return false
	})
	split := strings.Split(power, "-")
	min = split[0]
	max = split[1]
	return
}

func HandlePrice(price string) (min string, max string) {
	split := strings.Split(price, "-")
	fmt.Println("price is", price)
	min = split[0]
	max = split[1]
	return
}
